package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.itheima.common.PageInfo;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import com.itheima.thread.TokenThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    //添加分类
    @Override
    public boolean addCategory(Category category) {
        //雪花数生成id
        String id = IdUtil.getSnowflakeNextIdStr();

        category.setId(id);
        int res = categoryMapper.addCategory(category);
        return res == 1;
    }

    //查看分类
    @Override
    public List<Category> getList(Integer type) {
        List<Category> list = categoryMapper.getList(type);
        return list;
    }

    @Override
    //分页查询分类    下面的<Employee>是因为PageInfo自定义了一个泛型<T>
    public PageInfo<Category> page(Integer page, Integer pageSize) {
        //创建一个容器
        PageInfo<Category> pageInfo = new PageInfo<Category>();
        //分页公式    第几页 = （第几页-1） * 一页的个数
        Integer start = (page - 1) * pageSize;
        List<Category> categories = categoryMapper.page(start, pageSize);
        //records：当前页面内容，是个数组[]
        pageInfo.setRecords(categories);
        //size：每页显示条数
        pageInfo.setSize(pageSize);
        //current：当前页码
        pageInfo.setCurrent(page);

        //计算 total(总条数)(通过名字) 的方法
        long count = categoryMapper.countCategory();

        //total：总条数
        pageInfo.setTotal(count);
        return pageInfo;

    }


    //删除分类
    @Override
    public boolean deleteCategory(String id) {

        int res = categoryMapper.deleteCategory(id);

        return res > 0;
    }

    //修改分类
    @Override
    public boolean updateCategory(Category category) {

        category.setUpdateTime(LocalDateTime.now());

        String cuid = TokenThreadUtils.threadLocal.get().getId();

        category.setUpdateUser(cuid);

        int res = categoryMapper.updateCategory(category);

        return res == 1;
    }

    @Override
    public List<Category> getMobileList() {
        List<Category> mobileList = categoryMapper.getMobileList();
        return mobileList;
    }


}
